package bsi.vn.FirstApp;


import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Calendar; 
import java.util.Date;
import java.util.List;
import java.util.TimeZone;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import bsi.vn.Data.ContractAdapter;
import bsi.vn.Data.ContractData;
import bsi.vn.Data.ContractDetailData;
import bsi.vn.Data.CookieData;
import bsi.vn.Data.CustomerData;
import bsi.vn.Lib.Consts;
import bsi.vn.Lib.ProcessFunc;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.InflateException;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

@SuppressLint("ValidFragment")
public class ContractGeneralFragment extends Fragment {
	
	private int CID;
	private Activity context;
	private TextView tvContractID;
	private TextView tvContractNO;
	private TextView tvContractName;
	private TextView tvContractEDate;
	private TextView tvContractSDate;
	private TextView tvContractType;
	private TextView tvCustomerName;
	private TextView tvNote;
	private SimpleDateFormat dateFormat;
	private View tab1;
	
	public ContractGeneralFragment(int cID, Context c) {
		super();
		CID = cID;
		context = (Activity) c;
	}



	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
//		container.removeAllViews();
		
		if (tab1 != null) {
	        ViewGroup parent = (ViewGroup) tab1.getParent();
	        if (parent != null)
	            parent.removeView(tab1);
	    }
	    try {
	        tab1 = inflater.inflate(R.layout.fragment_contract_general, container, false);
	    } catch (InflateException e) {
	        Log.d("test", "Inflate Exception");
	    }
		
//		View tab1 = inflater.inflate(R.layout.fragment_contract_general, container, false);
//		TextView a = (TextView) tab1.findViewById(R.id.textView1);
//		a.setText(CID + "");
//		tvContractID = (TextView) tab1.findViewById(R.id.tvfcgCID);
		dateFormat = new SimpleDateFormat("dd/MM/yyyy");
		dateFormat.setTimeZone(TimeZone.getTimeZone("GMT"));
		
		tvContractNO = (TextView) tab1.findViewById(R.id.tvfcgCNO);
		tvContractName = (TextView) tab1.findViewById(R.id.tvfcgCName);
		tvContractEDate = (TextView) tab1.findViewById(R.id.tvfcgExpire);
		tvContractSDate = (TextView) tab1.findViewById(R.id.tvfcgSigned);
		tvContractType = (TextView) tab1.findViewById(R.id.tvfcgCType);
		tvCustomerName = (TextView) tab1.findViewById(R.id.tvfcgCusName);
		tvNote = (TextView) tab1.findViewById(R.id.tvfcgNote);
		myContractDetail myWebFetch = new myContractDetail();
		myWebFetch
				.execute(new String[] {CID+""});
		
		
		
		return tab1;
	}
	
	private class myContractDetail extends AsyncTask<String, String, String> {

		@Override
		protected String doInBackground(String... params) {
			String data = "";
			try {

				data = GetContractDetail(params[0]);
			} catch (Exception e) {
				e.printStackTrace();
			}
			return data;
		}

		@Override
		protected void onPostExecute(String result) {
			String loc_arResponse[] = result.split("\\|");
			int loc_iResponseCode = Integer.parseInt(loc_arResponse[0]);
			if (loc_iResponseCode == Consts.RC_LOGOUT) {
				startActivity(new Intent(context,
						LoginActivity.class));
				return;
			}
			if (loc_iResponseCode == Consts.RC_ERROR) {
				ProcessFunc.ShowSimpleDialog(context,
						"Error", loc_arResponse[1]);
				return;
			}

			try {
//				Log.d("test", loc_arResponse[1]);
				JSONArray jArray = new JSONArray(loc_arResponse[1]);
//				for (int i = 0; i < jArray.length(); i++) {
					JSONObject json_data = jArray.getJSONObject(0);
//					ContractDetailData coData = new ContractDetailData();
//					Log.d("test", "lengh " + jArray.length());
					int cid = json_data.getInt(Consts.SDB_CONTRACTID);
					String cno = json_data.getString(Consts.SDB_CONTRACTNO);

					String sda  = json_data.getString(Consts.SDB_SIGNEDDATE);

					String eda = json_data.getString(Consts.SDB_EXPIREDATE);

					String typ = json_data.getString(Consts.SDB_TYPE);

					String cus  = json_data.getString(Consts.SDB_CUSTOMER);

					String not = json_data.getString(Consts.SDB_CONTRACTNOTE);

					String can = json_data.getString(Consts.SDB_CONTRACTNAME);



//					tvContractID.setText(cid+"");
					tvContractNO.setText(cno);
					tvContractName.setText(can);
					tvContractSDate.setText(dateFormat.format(ProcessFunc.stringToDate(sda, "ddMMyyyyHHmm")));
					tvContractEDate.setText(dateFormat.format(ProcessFunc.stringToDate(eda, "ddMMyyyyHHmm")));
					tvContractType.setText(typ);
					tvCustomerName.setText(cus);
					tvNote.setText(not);
					
//					coData.setContractId(json_data
//							.getInt(Consts.SDB_CONTRACTID));
//					coData.setContractNo(json_data
//							.getString(Consts.SDB_CONTRACTNO));
//					coData.setExpireDate(json_data
//							.getString(Consts.SDB_EXPIREDATE));
//					coData.setCustomer(json_data.getString(Consts.SDB_CUSTOMER));


//				}
			} catch (JSONException e) {
				Log.e("test", "Error parsing data " + e.toString());
			}

			

			// lvTicket.setOnItemClickListener(new OnItemClickListener() {
			// @Override
			// public void onItemClick(AdapterView<?> parent, View view,
			// int position, long id) {
			// int TicketId = ticketData.get(position).getTicketId();
			// Intent i = new Intent(getApplicationContext(),
			// TicketDetailActivity.class);
			// i.putExtra("TicketId", TicketId);
			// startActivity(i);
			// }
			// });
		}

		@Override
		protected void onPreExecute() {
		}

		@Override
		protected void onProgressUpdate(String... text) {
		}

	}
	
	private String GetContractDetail(String contractID) {
		InputStream is = null;
		String result = "";
		try {
			HttpClient httpclient = new DefaultHttpClient();
			HttpPost httppost = new HttpPost(Consts.MAIN_URL);

			CookieData cookie = ProcessFunc
					.GetCookie(context);

			List<NameValuePair> nameValuePair = new ArrayList<NameValuePair>(4);
			nameValuePair.add(new BasicNameValuePair(Consts.V_FUNC,
					Consts.F_CONTRACTINFOMATION));
			nameValuePair.add(new BasicNameValuePair(Consts.V_USERID, String
					.valueOf(cookie.getUserId())));
			nameValuePair.add(new BasicNameValuePair(Consts.V_COOKIE, cookie
					.getCookie()));
			nameValuePair.add(new BasicNameValuePair(Consts.V_CONTRACTID, CID +""));


			httppost.setEntity(new UrlEncodedFormEntity(nameValuePair));
			HttpResponse response = httpclient.execute(httppost);
			HttpEntity entity = response.getEntity();
			is = entity.getContent();
		} catch (Exception e) {
			Log.e("log_tag", "Error in http connection " + e.toString());
		}

		try {
			BufferedReader reader = new BufferedReader(new InputStreamReader(
					is, "utf-8"), 16);
			StringBuilder sb = new StringBuilder();
			String line = null;
			while ((line = reader.readLine()) != null) {
				sb.append(line + "\n");
			}
			is.close();
			result = sb.toString();
		} catch (Exception e) {
			Log.e("test", "Error converting result " + e.toString());
		}
		return result;
	}
	

}
